import type { MockMethod } from 'vite-plugin-mock'
import type { API } from '../../src/types/api/response'
import type {
  ConfigGroupQuery,
  ConfigGroup, 
  CreateConfigGroup,
  UpdateConfigGroup
} from '@/types/api/config/configGroup'
import type {
  Config, 
  ConfigValueType,
  CreateConfig,
  UpdateConfig
} from '@/types/api/config/config'

// ------------ 常量定义 ------------
const valueTypes = [
  { value: 'string', label: '字符串' },
  { value: 'number', label: '数字' },
  { value: 'boolean', label: '布尔值' },
  { value: 'json', label: 'JSON' }
]

// 预定义真实的配置分组
const realConfigGroups = [
  {
    name: '系统配置',
    code: 'system',
    icon: 'setting',
    sort: 1,
    remark: '系统基本参数配置',
    configs: [
      {
        configName: '系统名称',
        configKey: 'sys.name',
        configValue: '通用后台管理系统',
        valueType: 'string',
        builtIn: true,
        remark: '系统显示名称，用于登录页面、首页等展示'
      },
      {
        configName: '系统版本',
        configKey: 'sys.version',
        configValue: 'v1.0.0',
        valueType: 'string',
        builtIn: true,
        remark: '当前系统版本号'
      },
      {
        configName: '系统描述',
        configKey: 'sys.description',
        configValue: '基于Vue3和TypeScript的通用后台管理系统',
        valueType: 'string',
        builtIn: false,
        remark: '系统简要描述，用于登录页面展示'
      },
      {
        configName: '系统Logo',
        configKey: 'sys.logo',
        configValue: '/assets/logo.png',
        valueType: 'string',
        builtIn: false,
        remark: '系统Logo地址，建议使用正方形透明底图片'
      },
      {
        configName: '首页路径',
        configKey: 'sys.indexPath',
        configValue: '/dashboard',
        valueType: 'string',
        builtIn: true,
        remark: '登录后跳转的首页路径'
      }
    ]
  },
  {
    name: '安全配置',
    code: 'security',
    icon: 'security',
    sort: 2,
    remark: '系统安全相关配置',
    configs: [
      {
        configName: '密码最小长度',
        configKey: 'security.password.minLength',
        configValue: '8',
        valueType: 'number',
        builtIn: true,
        remark: '用户密码最小长度限制'
      },
      {
        configName: '密码复杂度策略',
        configKey: 'security.password.policy',
        configValue: 'medium',
        valueType: 'string',
        builtIn: true,
        remark: '密码复杂度要求：simple(数字)、medium(数字+字母)、strong(数字+大小写字母+特殊字符)'
      },
      {
        configName: '密码过期天数',
        configKey: 'security.password.expireDays',
        configValue: '90',
        valueType: 'number',
        builtIn: false,
        remark: '密码过期时间，超过该天数需要重新修改密码，0表示永不过期'
      },
      {
        configName: '账号锁定阈值',
        configKey: 'security.account.lockThreshold',
        configValue: '5',
        valueType: 'number',
        builtIn: true,
        remark: '登录失败锁定阈值，超过该次数账号将被锁定'
      },
      {
        configName: '账号锁定时间',
        configKey: 'security.account.lockDuration',
        configValue: '30',
        valueType: 'number',
        builtIn: true,
        remark: '账号锁定持续时间(分钟)'
      },
      {
        configName: '允许同时登录',
        configKey: 'security.session.concurrent',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否允许同一账号同时登录'
      }
    ]
  },
  {
    name: '邮件配置',
    code: 'mail',
    icon: 'mail',
    sort: 3,
    remark: '系统邮件服务配置',
    configs: [
      {
        configName: 'SMTP服务器',
        configKey: 'mail.smtp.host',
        configValue: 'smtp.example.com',
        valueType: 'string',
        builtIn: false,
        remark: 'SMTP服务器地址'
      },
      {
        configName: 'SMTP端口',
        configKey: 'mail.smtp.port',
        configValue: '465',
        valueType: 'number',
        builtIn: false,
        remark: 'SMTP服务器端口'
      },
      {
        configName: '发件人邮箱',
        configKey: 'mail.from.address',
        configValue: 'system@example.com',
        valueType: 'string',
        builtIn: false,
        remark: '系统发送邮件的邮箱地址'
      },
      {
        configName: '发件人名称',
        configKey: 'mail.from.name',
        configValue: '系统管理员',
        valueType: 'string',
        builtIn: false,
        remark: '系统发送邮件时显示的发件人名称'
      },
      {
        configName: '邮箱账号',
        configKey: 'mail.username',
        configValue: 'system@example.com',
        valueType: 'string',
        builtIn: false,
        remark: 'SMTP服务器认证的用户名'
      },
      {
        configName: '邮箱密码',
        configKey: 'mail.password',
        configValue: '******',
        valueType: 'string',
        builtIn: false,
        remark: 'SMTP服务器认证的密码'
      },
      {
        configName: '启用SSL',
        configKey: 'mail.ssl.enabled',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否启用SSL安全连接'
      }
    ]
  },
  {
    name: '文件存储',
    code: 'storage',
    icon: 'file',
    sort: 4,
    remark: '文件上传存储相关配置',
    configs: [
      {
        configName: '存储模式',
        configKey: 'storage.mode',
        configValue: 'local',
        valueType: 'string',
        builtIn: true,
        remark: '文件存储模式：local(本地)、s3(云存储)、oss(阿里云)、cos(腾讯云)'
      },
      {
        configName: '上传目录',
        configKey: 'storage.local.path',
        configValue: './uploads',
        valueType: 'string',
        builtIn: false,
        remark: '本地存储模式下的文件保存路径'
      },
      {
        configName: '允许的文件类型',
        configKey: 'storage.allowedTypes',
        configValue: '.jpg,.jpeg,.png,.gif,.doc,.docx,.xls,.xlsx,.pdf,.zip,.rar',
        valueType: 'string',
        builtIn: false,
        remark: '允许上传的文件后缀名，用逗号分隔'
      },
      {
        configName: '最大上传大小',
        configKey: 'storage.maxSize',
        configValue: '10',
        valueType: 'number',
        builtIn: false,
        remark: '单个文件最大上传大小，单位MB'
      },
      {
        configName: '水印开关',
        configKey: 'storage.watermark.enabled',
        configValue: 'false',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否开启图片水印功能'
      }
    ]
  },
  {
    name: '界面设置',
    code: 'ui',
    icon: 'user',
    sort: 5,
    remark: '系统界面显示相关配置',
    configs: [
      {
        configName: '主题模式',
        configKey: 'ui.theme.mode',
        configValue: 'light',
        valueType: 'string',
        builtIn: false,
        remark: '默认主题模式：light(亮色)、dark(暗色)、auto(跟随系统)'
      },
      {
        configName: '主题颜色',
        configKey: 'ui.theme.color',
        configValue: '#1890ff',
        valueType: 'string',
        builtIn: false,
        remark: '系统主题色，影响按钮、链接等主要元素颜色'
      },
      {
        configName: '开启标签页',
        configKey: 'ui.tab.enabled',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否开启多标签页模式'
      },
      {
        configName: '固定顶栏',
        configKey: 'ui.header.fixed',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否固定顶部导航栏'
      },
      {
        configName: '固定菜单',
        configKey: 'ui.sidebar.fixed',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否固定侧边菜单栏'
      },
      {
        configName: '侧边栏Logo',
        configKey: 'ui.sidebar.logo',
        configValue: 'true',
        valueType: 'boolean',
        builtIn: false,
        remark: '是否在侧边栏显示Logo'
      }
    ]
  }
]

// ------------ 工具函数 ------------
/**
 * 生成配置分组
 */
const generateConfigGroup = (id: string, groupData: any): ConfigGroup => {
  return {
    id,
    name: groupData.name,
    code: groupData.code,
    icon: groupData.icon,
    sort: groupData.sort,
    remark: groupData.remark
  }
}

/**
 * 生成配置
 */
const generateConfig = (id: string, groupId: string, configData: any): Config => {
  return {
    id,
    groupId,
    configName: configData.configName,
    configKey: configData.configKey,
    configValue: configData.configValue,
    valueType: configData.valueType as ConfigValueType,
    builtIn: configData.builtIn,
    remark: configData.remark
  }
}

// ------------ 模拟数据 ------------
// 生成配置分组数据
const configGroups: ConfigGroup[] = realConfigGroups.map((group, index) => 
  generateConfigGroup(String(index + 1), group)
)

// 生成配置项数据
const configs: Config[] = []
realConfigGroups.forEach((group, groupIndex) => {
  group.configs.forEach((config, configIndex) => {
    configs.push(
      generateConfig(`${groupIndex + 1}-${configIndex + 1}`, String(groupIndex + 1), config)
    )
  })
})

// ------------ API 实现 ------------
/**
 * 获取配置分组列表
 */
const getConfigGroupListApi: MockMethod = {
  url: '/api/config/setting/groups',
  method: 'get',
  response: ({ query }: { query: ConfigGroupQuery }): API.Response<ConfigGroup[]> => {
    try {
      const { keyword } = query
      let filteredGroups = [...configGroups]

      if (keyword) {
        filteredGroups = filteredGroups.filter(
          group => group.name.includes(keyword) || group.code.includes(keyword)
        )
      }

      return {
        code: 200,
        success: true,
        message: 'ok',
        data: filteredGroups
      }
    } catch (error) {
      return {
        code: 500,
        success: false,
        message: '系统错误',
        data: []
      }
    }
  }
}

/**
 * 获取配置分组详情
 */
const getConfigGroupDetailApi: MockMethod = {
  url: '/api/config/group/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<ConfigGroup | null> => {
    const group = configGroups.find(item => item.id === query.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: group || null
    }
  }
}

/**
 * 创建配置分组
 */
const createConfigGroupApi: MockMethod = {
  url: '/api/config/group',
  method: 'post',
  response: ({ body }: { body: CreateConfigGroup }): API.Response<ConfigGroup | null> => {
    const { name, code, icon, sort, remark } = body

    // 检查配置分组编码是否已存在
    if (configGroups.some(item => item.code === code)) {
      return {
        code: 400,
        success: false,
        message: '配置分组编码已存在',
        data: null
      }
    }

    const newGroup: ConfigGroup = {
      id: String(configGroups.length + 1),
      name,
      code,
      icon,
      sort,
      remark: remark || ''
    }

    configGroups.push(newGroup)
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newGroup
    }
  }
}

/**
 * 更新配置分组
 */
const updateConfigGroupApi: MockMethod = {
  url: '/api/config/group/:id',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: UpdateConfigGroup }): API.Response<null> => {
    const index = configGroups.findIndex(item => item.id === query.id)
    if (index > -1) {
      // 处理可选字段，使用现有值作为默认值
      const currentGroup = configGroups[index];
      const name = body.name ?? currentGroup.name;
      const code = body.code ?? currentGroup.code;
      const icon = body.icon ?? currentGroup.icon;
      const sort = body.sort ?? currentGroup.sort;
      const remark = body.remark;

      // 检查配置分组编码是否已存在（排除自身）
      if (configGroups.some(item => item.id !== query.id && item.code === code)) {
        return {
          code: 400,
          success: false,
          message: '配置分组编码已存在',
          data: null
        }
      }

      // 更新配置分组
      configGroups[index] = {
        ...configGroups[index],
        name,
        code,
        icon,
        sort,
        remark
      }

      return {
        code: 200,
        success: true,
        message: '更新成功',
        data: null
      }
    }

    return {
      code: 404,
      success: false,
      message: '配置分组不存在',
      data: null
    }
  }
}

/**
 * 删除配置分组
 */
const deleteConfigGroupApi: MockMethod = {
  url: '/api/config/group/:id',
  method: 'delete',
  response: ({ query }: { query: { id: string } }): API.Response<null> => {
    const index = configGroups.findIndex(item => item.id === query.id)
    if (index > -1) {
      // 检查是否有关联的配置项
      if (configs.some(item => item.groupId === query.id)) {
        return {
          code: 400,
          success: false,
          message: '该配置分组下存在配置项，不能删除',
          data: null
        }
      }
      configGroups.splice(index, 1)
    }

    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 获取配置列表
 */
const getConfigListApi: MockMethod = {
  url: '/api/config/list',
  method: 'get',
  response: ({ query }: { query: any }): API.Response<{
    list: Config[]
    total: number
  }> => {
    const { groupId, keyword, page = 1, pageSize = 10 } = query
    let filteredConfigs = [...configs]

    if (groupId) {
      filteredConfigs = filteredConfigs.filter(config => config.groupId === groupId)
    }

    if (keyword) {
      filteredConfigs = filteredConfigs.filter(
        config => config.configName.includes(keyword) || config.configKey.includes(keyword)
      )
    }

    const pageNum = Number(page);
    const pageSizeNum = Number(pageSize);
    const startIndex = (pageNum - 1) * pageSizeNum;
    const endIndex = startIndex + pageSizeNum;
    const list = filteredConfigs.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredConfigs.length
      }
    }
  }
}

/**
 * 获取配置详情
 */
const getConfigDetailApi: MockMethod = {
  url: '/api/config/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<Config | null> => {
    const config = configs.find(item => item.id === query.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: config || null
    }
  }
}

/**
 * 创建配置
 */
const createConfigApi: MockMethod = {
  url: '/api/config',
  method: 'post',
  response: ({ body }: { body: CreateConfig }): API.Response<Config | null> => {
    const { groupId, configName, configKey, configValue, valueType, builtIn, remark } = body

    // 检查配置键是否已存在
    if (configs.some(item => item.configKey === configKey)) {
      return {
        code: 400,
        success: false,
        message: '配置键已存在',
        data: null
      }
    }

    const newConfig: Config = {
      id: String(configs.length + 1),
      groupId,
      configName,
      configKey,
      configValue,
      valueType,
      builtIn,
      remark: remark || ''
    }

    configs.push(newConfig)
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newConfig
    }
  }
}

/**
 * 更新配置
 */
const updateConfigApi: MockMethod = {
  url: '/api/config/:id',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: UpdateConfig }): API.Response<null> => {
    const index = configs.findIndex(item => item.id === query.id)
    if (index > -1) {
      const { groupId, configName, configKey, configValue, valueType, builtIn, remark } = body as any

      // 检查配置键是否已存在（排除自身）
      if (configKey && configs.some(item => item.id !== query.id && item.configKey === configKey)) {
        return {
          code: 400,
          success: false,
          message: '配置键已存在',
          data: null
        }
      }

      configs[index] = {
        ...configs[index],
        ...(groupId !== undefined && { groupId }),
        ...(configName !== undefined && { configName }),
        ...(configKey !== undefined && { configKey }),
        ...(configValue !== undefined && { configValue }),
        ...(valueType !== undefined && { valueType }),
        ...(builtIn !== undefined && { builtIn }),
        ...(remark !== undefined && { remark: remark || '' })
      }
    }

    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除配置
 */
const deleteConfigApi: MockMethod = {
  url: '/api/config/:id',
  method: 'delete',
  response: ({ query }: { query: { id: string }}): API.Response<null> => {
    const index = configs.findIndex(item => item.id === query.id)
    if (index > -1) {
      configs.splice(index, 1)
    }

    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

// ------------ 导出 ------------
export default [
  getConfigGroupListApi,
  getConfigGroupDetailApi,
  createConfigGroupApi,
  updateConfigGroupApi,
  deleteConfigGroupApi,
  getConfigListApi,
  getConfigDetailApi,
  createConfigApi,
  updateConfigApi,
  deleteConfigApi
] as MockMethod[] 